import { HttpException, HttpStatus, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
import { Repository } from 'typeorm';
import { CreatePostDto } from './dto/create-posts.dto';
import { UpdatePostDto } from './dto/update-posts.dto';
import { Posts } from './entities/posts.entity';

@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(Posts)
    private readonly postsRepository: Repository<Posts>
  ) {}

  findAll(paginationQuery: PaginationQueryDto) {
    const { limit, offset } = paginationQuery;

    return this.postsRepository.findAndCount({
      skip: offset,
      take: limit,
    });
  }

  async create(body: CreatePostDto) {
    const item = this.postsRepository.create(body)
    
    return this.postsRepository.save(item)
  }

  async findOne(id: string) {
    const dataItem = await this.postsRepository.find({
      where: {
        id: Number(id),
      }
    });
    if (!dataItem) {
      // throw new NotFoundError
      throw new HttpException(`找不到id为${id}的资源`, HttpStatus.NOT_FOUND);
      // throw new NotFoundException(`找不到id为${id}的资源`);
    }

    return dataItem;
  }

  async update(id: string, body: UpdatePostDto) {
    /* 如果表里面找不到对应的id，则直接返回undefined */
    const item = await this.postsRepository.preload({
      id: Number(id),
      ...body
    });

    if (!item) {
      throw new NotFoundException(`coffee #${id} not found`);
    }
    return this.postsRepository.save(item);
  }

  async remove(id: string) {
    const coffee = await this.findOne(id);

    return this.postsRepository.remove(coffee);
  }
}
